package com.weme.common.util

import android.animation.*
import android.content.Context
import android.graphics.Bitmap
import android.graphics.LinearGradient
import android.graphics.Rect
import android.graphics.Shader
import android.graphics.drawable.Drawable
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.AnticipateOvershootInterpolator
import android.view.animation.LinearInterpolator
import android.view.animation.TranslateAnimation
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.transition.Slide
import androidx.transition.TransitionManager
import androidx.transition.TransitionSet
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory
import com.google.gson.Gson
import com.makeramen.roundedimageview.RoundedImageView
import com.opensource.svgaplayer.*
import com.weme.alphapalyer.AnimConfig
import com.weme.alphapalyer.AnimView
import com.weme.alphapalyer.inter.IAnimListener
import com.weme.alphapalyer.util.FileUtil
import com.weme.common.view.SmoothImageView
import dev.kratos.api.user_server.v1.CountryInfo
import jp.wasabeef.glide.transformations.BlurTransformation
import java.io.File
import java.io.FileNotFoundException
import java.lang.ref.WeakReference
import java.net.URL

/**
 * @author Mr.w 2022/4/15.
 *
 * view拓展类
 *
 */
fun View.sp2px(spValue: Int): Int {
    val fontScale = resources.displayMetrics.scaledDensity
    return (spValue * fontScale + 0.5f).toInt()
}

fun View.dp2px(dp: Float): Int {
    val scale = resources.displayMetrics.density
    return (dp * scale + 0.5f).toInt()
}


var lastClickTime = 0L

fun View.isFastClick(): Boolean {
    if (System.currentTimeMillis() - lastClickTime < 500L) { //     Log.v("isFastClick")
        return true
    }
    lastClickTime = System.currentTimeMillis()
    return false
}

fun View.isFastClick(time: Long): Boolean {
    if (System.currentTimeMillis() - lastClickTime < time) { // Log.v("isFastClick")
        return true
    }
    lastClickTime = System.currentTimeMillis()
    return false
}

fun isFastClick(time: Long): Boolean {
    if (System.currentTimeMillis() - lastClickTime < time) { //    Log.v("isFastClick")
        return true
    }
    lastClickTime = System.currentTimeMillis()
    return false
}


// 防止快速点击
fun View.setOnFastClickListener(listener: View.OnClickListener) {
    setOnClickListener {
        if (this.isFastClick(1000)) return@setOnClickListener
        listener.onClick(this)
    }
}


// 防止快速点击
fun View.setOnFastClickListener(listener: View.OnClickListener, time: Long = 1000L) {
    setOnClickListener {
        if (this.isFastClick(time)) return@setOnClickListener
        listener.onClick(this)
    }
}

fun View.visible() { //    post {
    visibility = View.VISIBLE //    }
}

fun View.visibleAgain() { //    post {
    if (visibility != View.VISIBLE) visibility = View.VISIBLE //    }
}

fun View.gone() { //    post {
    visibility = View.GONE //    }
}

fun View.invisible() { //    post {
    visibility = View.INVISIBLE //    }
}

//通过boolean 设置图片隐藏显示
fun View.setVisible(boolean: Boolean) {
    if (boolean) {
        visibility = View.VISIBLE
    } else {
        visibility = View.GONE
    }
}

fun View.setInvisible(boolean: Boolean) {
    if (boolean) {
        visibility = View.VISIBLE
    } else {
        visibility = View.INVISIBLE
    }
}

fun View.fadeOut(duration: Long = 500) {
    val alphaAnimator = ObjectAnimator.ofFloat(this, View.ALPHA, 1f, 0f)
    alphaAnimator.duration = duration
    alphaAnimator.start()

    // 可选：在动画结束时隐藏 View
    alphaAnimator.addListener(object : AnimatorListenerAdapter() {
        override fun onAnimationEnd(animation: Animator) {
            super.onAnimationEnd(animation) // this@fadeOut.visibility = View.GONE
        }
    })
}


fun TextView.clearText() {
    text = ""
}

fun ImageView.loadImageWithPlaceholderAndTransformation(imageUrl: String?, blurRadius: Int, blurSampling: Int) {
    val contextRef = WeakReference(context) // 使用 WeakReference 存储 Context 引用


    contextRef.get()?.let {
        val requestOptions = RequestOptions.placeholderOf(com.example.resources.R.mipmap.icon_head_null).transform(GlideBlurTransformer(blurRadius, blurSampling)) // 使用 WeakReference 获取 Context
            .error(com.example.resources.R.mipmap.icon_head_null)
        Glide.with(it) // 使用 WeakReference 获取 Context
            .load(imageUrl).apply(requestOptions).into(this)
    }
}

fun ImageView.loadImage(imageUrl: String?) {
    Glide.with(context).load(imageUrl) //  .diskCacheStrategy(DiskCacheStrategy.ALL) // 根据需求设置缓存策略
        .into(this)
}

fun ImageView.loadUserInfoImage(imageUrl: String?) {
    Glide.with(context).load(imageUrl).sizeMultiplier(0.5f).override(context.deviceSize.width, context.deviceSize.height / 2).error(com.example.resources.R.mipmap.icon_mine_pic_null) //  .diskCacheStrategy(DiskCacheStrategy.ALL) // 根据需求设置缓存策略
        .into(this)
}

val factory: DrawableCrossFadeFactory = DrawableCrossFadeFactory.Builder().setCrossFadeEnabled(true).build() //聊天图片

fun ImageView.loadChatImage(imageUrl: String?) {
    Glide.with(context)

        .load(imageUrl).sizeMultiplier(0.8f).override(dp2px(160f), dp2px(160f)).transition(DrawableTransitionOptions.withCrossFade(factory)).error(com.example.resources.R.mipmap.icon_mine_pic_null) //  .diskCacheStrategy(DiskCacheStrategy.ALL) // 根据需求设置缓存策略
        .into(this)
}

//高斯模糊
fun SmoothImageView.loadImageWithPlaceholderAndTransformation(imageUrl: String?, blurRadius: Int, blurSampling: Int) {
    if (TextUtils.isEmpty(imageUrl)) {
        return
    }
    val contextRef = WeakReference(context) // 使用 WeakReference 存储 Context 引用

    val requestOptions = RequestOptions.placeholderOf(com.example.resources.R.mipmap.icon_head_null).transform(GlideBlurTransformer(blurRadius, blurSampling)) // 使用 WeakReference 获取 Context
        .error(com.example.resources.R.mipmap.icon_head_null)
    contextRef.get()?.let {
        Glide.with(it) // 使用 WeakReference 获取 Context
            .load(imageUrl).apply(requestOptions).into(this)
    }

}

val requestOptions = RequestOptions().placeholder(com.example.resources.R.mipmap.icon_head_null).error(com.example.resources.R.mipmap.icon_head_null)


//加载首页图片
fun ImageView.loadImageHome(imageUrl: String?) {
    if (TextUtils.isEmpty(imageUrl) ) {
        this.setImageResource(com.example.resources.R.mipmap.icon_home_null)
    } else {
        Glide.with(context)
            .load(imageUrl.toString()) //  .diskCacheStrategy(DiskCacheStrategy.ALL) // 根据需求设置缓存策略
            .placeholder(com.example.resources.R.mipmap.icon_home_null)
            .sizeMultiplier(0.9f).override(324, 500)
            .thumbnail(Glide.with(context).load(imageUrl)).
            into(this)
        this.tag = "0"
    }
}
fun ImageView.loadImageHomeWithBlur(imageUrl: String?) {
    if (TextUtils.isEmpty(imageUrl)) {
        this.setImageResource(com.example.resources.R.mipmap.icon_home_null)
    } else {
        Glide.with(context)
            .load(imageUrl.toString())
            .placeholder(com.example.resources.R.mipmap.icon_home_null)
            .sizeMultiplier(0.9f)
            .override(324, 500)
            .thumbnail(Glide.with(context).load(imageUrl))
            .apply(RequestOptions.bitmapTransform(BlurTransformation(25, 3))) // Add Gaussian blur
            .into(this)
        this.tag = "0"
    }
}


fun ImageView.loadImageMin(imageUrl: String?) {
    if (TextUtils.isEmpty(imageUrl)) {
        this.setImageResource(com.example.resources.R.mipmap.icon_head_null)
    } else {
        Glide.with(context).load(imageUrl.toString()) //  .diskCacheStrategy(DiskCacheStrategy.ALL) // 根据需求设置缓存策略
            .sizeMultiplier(0.9f).override(64, 64) .into(this)
    }
}

//普通加载
fun SmoothImageView.loadImage(imageUrl: String?) {
    if (TextUtils.isEmpty(imageUrl)) {
        this.setImageResource(com.example.resources.R.mipmap.icon_head_null)
    } else {
        Glide.with(context).load(imageUrl.toString()).apply(requestOptions) //  .diskCacheStrategy(DiskCacheStrategy.ALL) // 根据需求设置缓存策略
            .into(this)
    }
}

fun ImageView.loadImage(imageUrl: String?, radiusInPixels: Int) {
    Glide.with(context).load(imageUrl).apply(RequestOptions().transform(RoundedCorners(radiusInPixels))).into(this)
}

fun RoundedImageView.loadImage(imageUrl: String?) {
    if (TextUtils.isEmpty(imageUrl)) {
        this.setImageResource(com.example.resources.R.mipmap.icon_head_null)
    } else {
        Glide.with(context).load(imageUrl.toString()).apply(requestOptions).error(com.example.resources.R.mipmap.icon_head_null) //   .diskCacheStrategy(DiskCacheStrategy.ALL) // 根据需求设置缓存策略
            .into(this)
    }
}

fun RoundedImageView.loadImage(imageUrl: Bitmap) {

    Glide.with(context).load(imageUrl.toString()).apply(requestOptions).error(com.example.resources.R.mipmap.icon_head_null) //   .diskCacheStrategy(DiskCacheStrategy.ALL) // 根据需求设置缓存策略
        .into(this)

}

fun RoundedImageView.loadMineHead(imageUrl: String?) {
    if (TextUtils.isEmpty(imageUrl)) {
        this.setImageResource(com.example.resources.R.mipmap.avatar_placeholder)
    } else {
        Glide.with(context).load(imageUrl.toString()).apply(requestOptions) //   .diskCacheStrategy(DiskCacheStrategy.ALL) // 根据需求设置缓存策略
            .into(this)
    }
}

fun String.normalizeImageExtension(): String {
    val lowerCaseExtension = this.toLowerCase()
    if (lowerCaseExtension.endsWith(".jpg.jpg") || lowerCaseExtension.endsWith(".png")) {
        return this.substring(0, length - 4)
    }
    return this
}


//view是否显示
fun View.isVISIBLE(): Boolean {
    return visibility == View.VISIBLE
}

//view 做位移动画
fun ViewGroup.startTransitionSlide(view: View, gravity: Int = Gravity.TOP, visible: Int = View.VISIBLE, duration: Long = 250L) {
    TransitionManager.beginDelayedTransition(this, TransitionSet().also {
        it.addTransition(Slide(gravity))
        it.interpolator = AnticipateOvershootInterpolator()
        it.duration = duration
    })
    view.visibility = visible
}

fun View.isTrueOrFalseVisible(isTrue: Boolean, falseState: Int = View.GONE) {
    if (isTrue) {
        visible()
    } else {
        visibility = falseState
    }
}

fun View.ktGetDrawableId(id: Int) {
    ContextCompat.getDrawable(this.context, id)
}

fun View.ktGetDrawable(id: Int) {
    background = ContextCompat.getDrawable(context, id)
}

fun View.ktReturnDrawable(id: Int): Drawable {
    return ContextCompat.getDrawable(context, id)!!
}

fun View.ktColorBg(id: Int) {
    setBackgroundColor(ContextCompat.getColor(context, id))
}


fun View.ktVisibleView() {
    post {
        if (!isVISIBLE()) {
            visible()
        }
    }
}


fun View.ktGoneView() {
    post { gone() }
}

fun View.ktInvisibleView() {
    post { invisible() }
}

fun ViewGroup.ktVisibleAddView(view: View) {
    post {
        if (!isVISIBLE()) visible()
        addView(view)
    }
}


fun ViewGroup.ktVisibleAddViewV2(view: View) {
    post {
        if (!isVISIBLE()) visible()
        removeAllViews()
        addView(view)
    }
}

fun ViewGroup.ktRAddView(view: View) {
    post {
        if (!isVISIBLE()) visible()
        removeAllViews()
        addView(view)
    }
}

fun ViewGroup.ktRemoveView(view: View) {
    post {
        removeView(view)
    }
}

fun ViewGroup.ktGoneRemoveView(view: View) {
    post {
        view.gone()
        removeView(view)
    }
}

fun View.setViewAplha(view: View?) {
    if (null == view) {
        return
    }
    view.alpha = 0.5f
}


/** 是否包含此标记 */
infix fun Int.contains(i: Int): Boolean = hasFlag(i)

/**是否含有此标记*/
infix fun Int.hasFlag(i: Int): Boolean { //含有：101 & 100 = 100
    //不含有：101 & 111 = 101
    return this and i == i
}


/** 在屏幕中的位置 */
fun View.getScreenRect(rect: Rect? = null): Rect {
    val xyArray = IntArray(2)
    this.getLocationOnScreen(xyArray)

    val result = rect ?: Rect()
    result.set(xyArray[0], xyArray[1], xyArray[0] + this.width, xyArray[1] + this.height)
    return result
}

fun createTranslate(
    view: View,
    fromGravity: Int,
    toGravity: Int,
    duration: Long = 500,
    fillAfter: Boolean = true,
): TranslateAnimation { //    if (fromGravity contains Gravity.RELATIVE_LAYOUT_DIRECTION || toGravity contains Gravity.RELATIVE_LAYOUT_DIRECTION) {
    //        LkLog.w { "警告，暂未支持根据“START、END”和“是否阿拉伯语”区分左右动画" }
    //    }
    //计算到屏幕外的偏移，view移动此距离后到屏幕外
    val viewRect = view.getScreenRect()
    val topOffset = 0f - viewRect.bottom
    val bottomOffset = view.resources.displayMetrics.ydpi - viewRect.top
    val leftOffset = 0f - viewRect.right
    val rightOffset = view.resources.displayMetrics.xdpi - viewRect.left //		LkLog.d { "位移计算：$topOffset $bottomOffset $leftOffset $rightOffset" }

    val fromX = when {
        fromGravity contains (Gravity.AXIS_PULL_BEFORE shl Gravity.AXIS_X_SHIFT) -> leftOffset
        fromGravity contains (Gravity.AXIS_PULL_AFTER shl Gravity.AXIS_X_SHIFT) -> rightOffset
        fromGravity contains (Gravity.AXIS_SPECIFIED shl Gravity.AXIS_X_SHIFT) -> 0f
        else -> 0f
    }
    val fromY = when {
        fromGravity contains (Gravity.AXIS_PULL_BEFORE shl Gravity.AXIS_Y_SHIFT) -> topOffset
        fromGravity contains (Gravity.AXIS_PULL_AFTER shl Gravity.AXIS_Y_SHIFT) -> bottomOffset
        fromGravity contains (Gravity.AXIS_SPECIFIED shl Gravity.AXIS_Y_SHIFT) -> 0f
        else -> 0f
    }
    val toX = when {
        toGravity contains (Gravity.AXIS_PULL_BEFORE shl Gravity.AXIS_X_SHIFT) -> leftOffset
        toGravity contains (Gravity.AXIS_PULL_AFTER shl Gravity.AXIS_X_SHIFT) -> rightOffset
        toGravity contains (Gravity.AXIS_SPECIFIED shl Gravity.AXIS_X_SHIFT) -> 0f
        else -> 0f
    }
    val toY = when {
        toGravity contains (Gravity.AXIS_PULL_BEFORE shl Gravity.AXIS_Y_SHIFT) -> topOffset
        toGravity contains (Gravity.AXIS_PULL_AFTER shl Gravity.AXIS_Y_SHIFT) -> bottomOffset
        toGravity contains (Gravity.AXIS_SPECIFIED shl Gravity.AXIS_Y_SHIFT) -> 0f
        else -> 0f
    }
    return TranslateAnimation(fromX.toFloat(), toX.toFloat(), fromY.toFloat(), toY.toFloat()).apply {
        this.duration = duration
        this.fillAfter = fillAfter
    }

}

fun RecyclerView.setVerticalLayoutManager() {
    layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
}

fun RecyclerView.setHorizontalLayoutManager() {
    layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
}


fun TextView.setGradientText(startColorResId: Int, endColorResId: Int) {
    val startColor = ContextCompat.getColor(context, endColorResId)
    val endColor = ContextCompat.getColor(context, startColorResId)

    // 创建线性渐变
    val gradientShader = LinearGradient(0f, 0f, 0f, height.toFloat(), // 注意这里高度使用 TextView 的高度
        startColor, endColor, Shader.TileMode.CLAMP)

    // 获取文本画笔
    val textPaint = paint

    // 应用渐变到文本画笔
    textPaint.shader = gradientShader

    // 监听视图布局完成
    viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
        override fun onGlobalLayout() { // 移除监听器，以免重复调用
            viewTreeObserver.removeOnGlobalLayoutListener(this)

            // 更新渐变效果，此时 TextView 的高度已知
            textPaint.shader = LinearGradient(0f, 0f, width.toFloat(), height.toFloat(), startColor, endColor, Shader.TileMode.CLAMP)
        }
    })
}

fun View.updateMarginLayoutParams(bottomMargin: Int) {
    val layoutParams = this.layoutParams

    if (layoutParams is ViewGroup.MarginLayoutParams) {
        val marginLayoutParams = layoutParams
        marginLayoutParams.bottomMargin = bottomMargin
        this.layoutParams = marginLayoutParams
    }
}


fun View.startCountdown(maxProgress: Int, onProgressUpdate: (Float) -> Unit, onComplete: () -> Unit): ValueAnimator {
    var countdownAnimator = ValueAnimator.ofFloat(0f, 100f)
    countdownAnimator?.duration = maxProgress * 1000L
    countdownAnimator?.interpolator = LinearInterpolator()
    countdownAnimator?.repeatCount = 0
    countdownAnimator?.addUpdateListener { animation ->
        onProgressUpdate(animation.animatedValue as Float)
    }
    countdownAnimator?.addListener(object : AnimatorListenerAdapter() {
        override fun onAnimationEnd(animation: Animator) {
            super.onAnimationEnd(animation)
            onComplete()
        }
    })
    countdownAnimator?.start()

    // 在 View 销毁时停止计时器以避免内存泄漏
    this.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
        override fun onViewAttachedToWindow(view: View) { // Do nothing
        }

        override fun onViewDetachedFromWindow(view: View) {
            countdownAnimator?.cancel()
            countdownAnimator?.removeAllListeners()
            countdownAnimator = null
        }
    })

    return countdownAnimator
}

fun RecyclerView.smoothScrollToBottom() {
    val itemCount = this.adapter?.itemCount ?: 0
    if (itemCount > 0) {
        this.smoothScrollToPosition(itemCount - 1)
    }
}

fun RecyclerView.scrollToBottom() {
    val itemCount = adapter?.itemCount ?: 0
    if (itemCount > 0) {
        scrollToPosition(itemCount - 1)
    }
}


fun SVGAImageView.playSVGA(url: String, mSVGACallback: SVGACallback, parseCompletion: SVGAParser.ParseCompletion) {
    try {
        SVGAParser.shareParser().decodeFromURL(URL(url), parseCompletion, null)
        callback = mSVGACallback
    } catch (e: FileNotFoundException) {
        e.printStackTrace()
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

fun SVGAImageView.playSVGAFromAssets(fileName: String) {
    val parser = SVGAParser(this.context)
    parser.decodeFromAssets(fileName+".svga", object : SVGAParser.ParseCompletion {
        override fun onComplete(videoItem: SVGAVideoEntity) {
            val drawable = SVGADrawable(videoItem)
            this@playSVGAFromAssets.setImageDrawable(drawable)

            this@playSVGAFromAssets.startAnimation()

        }

        override fun onError() {
        }
    }, object : SVGAParser.PlayCallback {
        override fun onPlay(file: List<File>) {
        }
    })
}

var gson = Gson()
fun getCountryBean(countryCode: String?): CountryInfo? {
    val countryBean = AppMkHelper.decodeString("country_$countryCode")
    return gson.fromJson(countryBean, CountryInfo::class.java)
}


fun View.fadeIn(duration: Long = 300) {
    val animator = ValueAnimator.ofFloat(0f, 1f)
    animator.duration = duration
    animator.interpolator = AccelerateDecelerateInterpolator()
    animator.addUpdateListener { animation ->
        val alpha = animation.animatedValue as Float
        this.alpha = alpha
    }
    animator.start()
}


fun setNameAge(originalText: String, maxName: Int = 12): String {

    val commaIndex = originalText.indexOf(',')
    return if (commaIndex >= maxName) {
        val name = originalText.substring(0, commaIndex)
        val age = originalText.substring(commaIndex + 1)
        val displayName = if (name.length > maxName) {
            name.substring(0, maxName - 1) + "…"
        } else {
            name
        }
        "$displayName,$age"
    } else {
        originalText
    }
}

fun AnimView.loadVideoFromAssets(videoFileName: String, md5: String, callback: () -> Unit) {
    val file = File("${FileUtils.fileUrl}/$videoFileName")
    val fileMD5 = FileUtil.getFileMD5(file)
    if (md5 == fileMD5) { //如果md5不匹配 代表文件不完整
        startPlay(file, callback)
    } else {
        FileUtils.deleteFile(file)
        callback.invoke()
    }

    setAnimListener(object : IAnimListener {
        override fun onVideoStart() {
            post {
                visible()
            }
        }

        override fun onVideoRender(frameIndex: Int, config: AnimConfig?) {

        }

        override fun onVideoComplete() {
            post {
                gone()
            }

            setAnimListener(null)
        }

        override fun onVideoDestroy() {

        }

        override fun onFailed(errorType: Int, errorMsg: String?) {

        }

    })
}


fun View.zoomIn(duration: Long = 300, scale: Float = 1.2f) {
    val scaleX = PropertyValuesHolder.ofFloat(View.SCALE_X, scale)
    val scaleY = PropertyValuesHolder.ofFloat(View.SCALE_Y, scale)
    val animator = ObjectAnimator.ofPropertyValuesHolder(this, scaleX, scaleY)
    animator.duration = duration
    animator.start()
}

// 扩展函数：缩小动画
fun View.zoomOut(duration: Long = 300, scale: Float = 1.0f) {
    val scaleX = PropertyValuesHolder.ofFloat(View.SCALE_X, scale)
    val scaleY = PropertyValuesHolder.ofFloat(View.SCALE_Y, scale)
    val animator = ObjectAnimator.ofPropertyValuesHolder(this, scaleX, scaleY)
    animator.duration = duration
    animator.start()
}

// 扩展属性，用于存储当前的 AnimatorSet
private var View.currentAnimatorSet: AnimatorSet?
    get() = getTag(com.weme.common.R.id.animator_set_tag) as? AnimatorSet
    set(value) = setTag(com.weme.common.R.id.animator_set_tag, value)

// 扩展函数，启动循环动画
fun View.animateScaleAndFadeLoop() { // 如果当前有动画在进行，先取消它
    currentAnimatorSet?.cancel()

    // 创建缩放和透明度动画
    val scaleX = ObjectAnimator.ofFloat(this, "scaleX", 1f, 1.2f)
    val scaleY = ObjectAnimator.ofFloat(this, "scaleY", 1f, 1.2f)
    val alpha = ObjectAnimator.ofFloat(this, "alpha", 1f, 0f)

    // 动画集合
    val animatorSet = AnimatorSet().apply {
        duration = 800L
        interpolator = AnticipateOvershootInterpolator()
        playTogether(scaleX, scaleY, alpha)
        addListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(animation: Animator) { // 动画开始时的操作
            }

            override fun onAnimationEnd(animation: Animator) { // 动画结束时，重新开始动画
                this@animateScaleAndFadeLoop.animateScaleAndFadeLoop()
            }

            override fun onAnimationCancel(animation: Animator) { // 动画取消时的操作
            }

            override fun onAnimationRepeat(animation: Animator) { // 动画重复时的操作
            }
        })
    }

    // 保存当前动画
    currentAnimatorSet = animatorSet

    // 启动动画
    animatorSet.start()
}

// 扩展函数，停止动画
fun View.stopAnimation() {
    currentAnimatorSet?.cancel()
    currentAnimatorSet = null
}


